package com.hmall.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.utils.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的用户信息
        String userId = request.getHeader("user-info");
        //2.如果不空存到ThreadLocal
        if (StrUtil.isNotBlank(userId)) {
            UserContext.setUser(Long.parseLong(userId));
        }
        System.out.println("UserInfoInterceptor:user:" + userId);
        //3.放行
        return true;
    }

    //    postHandle：在请求处理之后但在视图渲染之前调用。
//    afterCompletion：在整个请求处理完成之后调用，即在视图渲染完成之后调用。
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }

}